import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpStatus,
  Logger,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { ErrorCode } from '../constants/error-code.enum';

/**
 * 全局异常过滤器
 * 捕获所有未处理的异常
 */
@Catch()
export class AllExceptionFilter implements ExceptionFilter {
  private readonly logger = new Logger(AllExceptionFilter.name);

  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    // 记录详细错误日志
    this.logger.error(
      `未处理的异常: [${request.method}] ${request.url}`,
      JSON.stringify({
        message: exception.message,
        stack: exception.stack,
        body: request.body,
        query: request.query,
        params: request.params,
      }),
    );

    // 返回统一格式
    response.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
      code: ErrorCode.INTERNAL_SERVER_ERROR,
      message: '服务器内部错误',
      data: null,
      timestamp: Date.now(),
      path: request.url,
    });
  }
}



